<%-- 
    Document   : profile
    Created on : 18-nov-2013, 11.35.34
    Author     : Ilo
--%>

<%@page import="it.evento.utils.genpage.BlogPost"%>
<%@page import="it.evento.utils.genpage.Article"%>
<%@page import="java.text.DateFormat"%>
<%@page import="java.util.Date"%>
<%@page import="java.text.SimpleDateFormat"%>
<%@page import="it.evento.Users"%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%
    boolean isLoggedUser = false;
    Users loggedUser = null;

    if (session.getAttribute("loggedUser") != null) {
        loggedUser = (Users) session.getAttribute("loggedUser");
        isLoggedUser = true;
    } else {
        isLoggedUser = false;
        response.sendRedirect("index.jsp");
    }
%>
<!DOCTYPE html>
<html dir="ltr" lang="it-IT">
    <head>
        <title>EvenTO::Profilo</title>

        <jsp:include page="html/metadata.jsp"/>
        
        <script lang="javascript">
            $(document).ready(function() {
                var tagsMap = {};
                var tagsArr = [];
                
                /* Load profile info */
                $.post("Controller",
                        {type: "loadProfileInfo"},
                        function(data) {
                            /* Profile Infos */
                            if (data.profileInfos.photo !== "")
                                $(".profile-photo").prop("src", data.profileInfos.photo);
                            
                            $("#txtUsername").html(data.profileInfos.username);
                            $("#txtUserTypeName").html(data.profileInfos.typename);

                            if(data.profileInfos.type===1)
                                $("#chkUpgrade").attr("disabled", "disabled");
                            if(data.profileInfos.upgrade)
                                $("#chkUpgrade").attr("checked", "checked");

                            $("#txtName").val(data.profileInfos.name);
                            $("#txtSurname").val(data.profileInfos.surname);

                            $("#birthDatePicker").val(data.profileInfos.birth);
                            $("#birthDatePicker").datepicker(DATE_PICKER_DEFAULT_SETTINGS);

                            $("#txtInfo").html(data.profileInfos.info);
                            /* /Profile Infos */
                            
                            /* Events Infos */
                            $("#txtCompany").val(data.eventsInfos.company);
                            
                            var autoCompleteData = $.map($.parseJSON(data.eventTypes), function(val, i) {
                                                        return {
                                                            label: val,
                                                            value: i
                                                        };
                                                    });
                            
                            $.each(autoCompleteData, function(i, item) {
                                tagsMap[item.value] = item.label;
                            });
                            
                            if(data.eventsInfos.tags !== "") {
                                $.each(split(data.eventsInfos.tags), function(i, item) {
                                    createTag(tagFromCode(item), $("#tag-list"));
                                });
                            }
                            
                            $("#txtAddTag").autocomplete({
                                minLength: 0,
                                source: function( request, response ) {
                                    // delegate back to autocomplete, but extract the last term
                                    response( $.ui.autocomplete.filter(
                                      autoCompleteData, extractLast( request.term ) ) );
                                },
                                focus: function(event, ui) {
                                    // prevent value inserted on focus
                                    return false;
                                },
                                select: function(event, ui) {
                                    var terms = split($("#txtAddTag").val());
                                    // remove the current input
                                    terms.pop();
                                    // add the selected item
                                    terms.push(ui.item.label);
                                    // add placeholder to get the comma-and-space at the end
                                    terms.push("");
                                    $("#txtAddTag").val(terms.join( ", " ));
                                    
                                    return false;
                                }
                              })
                              .data( "ui-autocomplete" )._renderItem = function( ul, item ) {
                                return $( "<li>" )
                                  .append( "<a>" + item.label + "</a>" )
                                  .appendTo( ul );
                              };
                            /* /Events Infos */
                        },
                        "json");
                /* /Load profile info */
                
                /* Save profile image */
                $('.profile-photo').click(function(e) {
                    var strHtml = "<div class='ui-widget hide' id='photo-error'>"
                                     + "<div class='ui-state-error ui-corner-all' style='margin-top: 20px; padding: 0 .7em;'>"
                                         + "<p><span class='ui-icon ui-icon-alert' style='float: left; margin-right: .3em;'></span>"
                                           + "<b class='error-text'></b></p>"
                                        + "</div>"
                                        + "<br>"
                                    + "</div>"
                                    + "<form id='frmProfilePhotoUpload' action='UploadController?profilephoto' method='post' enctype='multipart/form-data'>"
                                        + "<input type='file' name='photo' />"
                                    + "</form>";
                    
                    $('#modal-window .modal-title').html("Upload Immagine Profilo!");
                    $('#modal-window #modal-message').html(strHtml);
                    $('#modal-window .modal-footer').removeClass('hide');
                    $('#modal-window #btnModalNo').html("Chiudi");
                    $('#modal-window #btnModalOk').html("Carica")
                                                  .click(function(e) {
                                                      $('#frmProfilePhotoUpload').submit();
                                                  });
                    $('#modal-window').modal('show');
                });
                /* /Save profile image */
                
                /* Save info */
                $("#frmProfileInfoChanges").submit(function(e) {
                    e.preventDefault();
                    var goOn = true;
                    
                    $("#profile-error .error-text").html("");
                    $("#profile-error").addClass("hide");
                    
                    if($.trim($("#txtName").val())==="") {
                        if($("#profile-error .error-text").html() !== "")
                            $("#profile-error .error-text").append("<br>");
                        
                        $("#profile-error .error-text").append("Errore: Il nome &egrave; obbligatorio.");
                        $("#profile-error").removeClass("hide");
                        
                        goOn = false;
                    }
                    if($.trim($("#txtSurname").val())==="") {
                        if($("#profile-error .error-text").html() !== "")
                            $("#profile-error .error-text").append("<br>");
                        
                        $("#profile-error .error-text").append("Errore: Il cognome &egrave; obbligatorio.");
                        $("#profile-error").removeClass("hide");
                        
                        goOn = false;
                    }
                    if($.trim($("#birthDatePicker").val())==="") {
                        if($("#profile-error .error-text").html() !== "")
                            $("#profile-error .error-text").append("<br>");
                        
                        $("#profile-error .error-text").append("Errore: Seleziona una data corretta.");
                        $("#profile-error").removeClass("hide");
                        
                        goOn = false;
                    }
                    
                    if(!goOn) return false;
                    
                    $.post("Controller",
                           {type: "saveProfileInfoChanges",
                            upgrade: $("#chkUpgrade").is(":checked"),
                            name: $("#txtName").val(),
                            surname: $("#txtSurname").val(),
                            birth: $("#birthDatePicker").val(),
                            info: $("#txtInfo").val()},
                           function(data) {
                               if(data.status === 1) {
                                   $("#profile-error .error-text").html(data.message);
                                   $("#profile-error").removeClass("hide");
                               }
                           },
                           "json");
                });
                /* /Save info */
                
                /* Save events */
                $("#frmEventsChanges").submit(function(e) {
                    e.preventDefault();
                    
                    $("#events-error .error-text").html("");
                    $("#events-error").addClass("hide");
                    
                    $.post("Controller",
                          {type: "saveEventsChanges",
                           company: $("#txtCompany").val(),
                           tags: JSON.stringify(tagsArr)},
                          function(data) {
                               if(data.status === 1) {
                                   $("#events-error .error-text").html(data.message);
                                   $("#events-error").removeClass("hide");
                               }
                          },
                          "json");
                });
                /* /Save events */

                /* Save password */
                $("#frmPasswordChanges").submit(function(e) {
                    e.preventDefault();
                    var goOn = true;
                    
                    $("#pwd-error .error-text").html("");
                    $("#pwd-error").addClass("hide");
                    
                    if($.trim($("#txtPwdOld").val())==="") {
                        if($("#pwd-error .error-text").html() !== "")
                            $("#pwd-error .error-text").append("<br>");
                        
                        $("#pwd-error .error-text").append("Errore: La vecchia password non &egrave; corretta.");
                        $("#pwd-error").removeClass("hide");
                        
                        goOn = false;
                    }
                    if($.trim($("#txtPwdNew1").val())==="" || $.trim($("#txtPwdNew2").val())==="") {
                        if($("#pwd-error .error-text").html() !== "")
                            $("#pwd-error .error-text").append("<br>");
                        
                        $("#pwd-error .error-text").append("Errore: La nuova password &egrave; obbligatoria.");
                        $("#pwd-error").removeClass("hide");
                        
                        goOn = false;
                    }
                    
                    if(!goOn) return false;
                    goOn = true;
                    
                    var pwdOld = $.sha1($("#txtPwdOld").val()),
                        pwd1 = $.sha1($("#txtPwdNew1").val()),
                        pwd2 = $.sha1($("#txtPwdNew2").val());
                                        
                    if(pwd1 !== pwd2) {
                        if($("#pwd-error .error-text").html() !== "")
                            $("#pwd-error .error-text").append("<br>");
                        
                        $("#pwd-error .error-text").append("Errore: Le due password devono essere uguali!");
                        $("#pwd-error").removeClass("hide");
                        
                        goOn = false;
                    }
                    
                    if(!goOn) return false;
                    
                    $.post("Controller",
                           {type: "savePasswordChanges",
                            pwdOld: pwdOld,
                            pwdNew1: pwd1,
                            pwdNew2: pwd2},
                           function(data) {
                               if(data.status === 1) {
                                   $("#pwd-error .error-text").html(data.message);
                                   $("#pwd-error").removeClass("hide");
                               }
                           },
                           "json");
                });
                /* /Save password */

                /* Tag Handler */
                function split(val) {
                    return val.split(/,\s*/);
                }
                function extractLast(term) {
                    return split(term).pop();
                }
                
                function tagFromCode(code) {
                    return tagsMap[code];
                }
                function codeFromTag(txt) {
                    var idx = -1;
                    txt = txt.replace("&amp;", "&");
                    
                    $.each(tagsMap, function(i, item) {
                        if(item === txt) {
                            idx = i;
                            return false;
                        }
                    });
                    
                    return idx;
                }
                
                function createTag(txt, parent) {
                    var str = "";
                    str += "<span class='tag-label'>";
                        str += "<span class='text'>" + txt + "</span>";
                        str += "<span class='close'>X</span>";
                    str += "</span>";

                    parent.html(parent.html() + str);
                    
                    $(".tag-label .close").bind("click", removeTag);
                    
                    addUniqueTagVal(txt);
                }
                
                function addUniqueTagVal(txt) {
                    tagsArr.push(parseInt(codeFromTag(txt)));
                }
                
                $(".tag-label .close").click(removeTag);
                function removeTag(e) {
                    var label = $(e.target).parent();
                    var txt = label.find('.text').html();
                    label.remove();
                    
                    code = parseInt(codeFromTag(txt));
                    position = $.inArray(code, tagsArr);
                    if(~position) tagsArr.splice(position, 1);
                }

                $("#btnAddTag").click(function(e) {
                    var txt = $("#btnAddTag").parent().find("input");
                    
                    $.each(split(txt.val()), function(i, item) {
                        if(item !== "")
                            createTag(item, $("#tag-list"));
                    });
                    txt.val("");
                });
                /* /Tag Handler */
            });
        </script>
    </head>
    <body>
        <div id="fb-root"></div>

        <div id="evento-main">
            <!-- header -->
            <jsp:include page="html/header.jsp" />
            <!-- /header -->

            <!-- top-menu -->
            <%@include file="html/top-menu.jsp" %>
            <!-- /top-menu -->

            <div class="evento-sheet clearfix">
                <div class="evento-layout-wrapper">
                    <div class="evento-content-layout">
                        <div class="evento-content-layout-row">
                            <div class="evento-layout-cell evento-content">
                                <article class="evento-post evento-article">
                                    <div class="evento-postmetadataheader">
                                        <h2 class="evento-postheader">Profilo</h2>
                                    </div>
                                    
                                    <div class="evento-postcontent evento-postcontent-0 clearfix">
                                        <div class="row profile">
                                            <div class="col-sm-4">
                                                <img src="images/no-avatar.jpg" alt="Foto profilo" class="thumbnail profile-photo">
                                                <br>
                                                <div class="profile-buttons">
                                                    <div class="gp-badge">
                                                        <img src="" class="gp-img hide" />
                                                        <div class="gp-info">
                                                            <div id="gp-hello"></div>
                                                            <div class="gp-login-button">
                                                                <span class="g-signin"
                                                                    data-callback="googlePlusAccessHandler"
                                                                    data-clientid="1092245667811-a3jaker2bjn4jupg288oqvhloholl57h.apps.googleusercontent.com"
                                                                    data-cookiepolicy="single_host_origin"
                                                                    data-approvalprompt="auto"
                                                                    data-requestvisibleactions="http://schemas.google.com/AddActivity"
                                                                    data-scope="https://www.googleapis.com/auth/plus.login"
                                                                    data-theme="dark"
                                                                    data-width="standard"
                                                                    data-height="standard">
                                                                </span>
                                                            </div>
                                                            <a class="evento-button gp-logout-button hide" href="">Esci</a>
                                                        </div>
                                                    </div>
                                                    <br>
                                                    <div class="fb-badge">
                                                        <img src="" class="fb-img" />
                                                        <div class="fb-info">
                                                            <div id="fb-hello"></div>
                                                            <div class="fb-login-button" 
                                                                data-max-rows="1" 
                                                                data-size="xlarge" 
                                                                data-show-faces="false" 
                                                                data-auto-logout-link="true">
                                                            </div>
                                                        </div>
                                                    </div>
                                                </div>
                                            </div>
                                            <div class="col-sm-8">
                                                <div class='ui-widget <%= (request.getParameter("ok")!=null && request.getParameter("ok").equals("ok")) ? "" : "hide" %>'>
                                                    <div class='ui-state-highlight ui-corner-all' style='margin-top: 20px; padding: 0 .7em;'>
                                                        <p><span class='ui-icon ui-icon-info' style='float: left; margin-right: .3em;'></span>
                                                        <b>Modifiche apportate correttamente</b></p>
                                                    </div>
                                                    <br>
                                                </div>
                                                <article class="evento-post evento-article">
                                                    <div class="evento-postmetadataheader">
                                                        <h2 class="evento-postheader">Profilo</h2>
                                                    </div>
                                                    <div class="evento-postcontent evento-postcontent-0 clearfix">
                                                        <div class="evento-content-layout">
                                                            <div class="evento-content-layout-row">
                                                                <div class="evento-layout-cell layout-item-0" style="width: 100%">
                                                                    <div class='ui-widget hide' id="profile-error">
                                                                        <div class='ui-state-error ui-corner-all' style='margin-top: 20px; padding: 0 .7em;'>
                                                                            <p><span class='ui-icon ui-icon-alert' style='float: left; margin-right: .3em;'></span>
                                                                            <b class="error-text"></b></p>
                                                                        </div>
                                                                        <br>
                                                                    </div>
                                                                    <form id="frmProfileInfoChanges">
                                                                        <span class="col-sm-4">Username:</span>
                                                                        <span class="col-sm-8" id="txtUsername"></span>
                                                                        <br>
                                                                        <span class="col-sm-4">Tipo:</span>
                                                                        <span class="col-sm-5" id="txtUserTypeName"></span>
                                                                        <span class="col-sm-3"><input type="checkbox" name="chkUpgrade" id="chkUpgrade"/> Upgrade?</span>
                                                                        <br>
                                                                        <span class="col-sm-4">Nome:</span>
                                                                        <span class="col-sm-8"><input type="text" name="txtName" id="txtName" value="" class="form-control" /></span>
                                                                        <br>
                                                                        <span class="col-sm-4">Cognome:</span>
                                                                        <span class="col-sm-8"><input type="text" name="txtSurname" id="txtSurname" value="" class="form-control" /></span>
                                                                        <br>
                                                                        <span class="col-sm-4">Data Nascita</span>
                                                                        <span class="col-sm-8"><input type="text" name="txtBirth" id="birthDatePicker" value="" class="form-control" /></span>
                                                                        <br>
                                                                        <span class="col-sm-4">Informazioni:</span>
                                                                        <span class="col-sm-8"><textarea name="txtInfo" id="txtInfo" class="form-control"></textarea></span>
                                                                        <br>
                                                                        <span class="col-sm-12" style="text-align:center"><input type="submit" class="evento-button" value="Salva Modifiche"/></span>
                                                                    </form>
                                                                </div>
                                                            </div>
                                                        </div>
                                                    </div>
                                                </article>
                                                
                                                <article class="evento-post evento-article">
                                                    <div class="evento-postmetadataheader">
                                                        <h2 class="evento-postheader">Eventi</h2>
                                                    </div>
                                                    <div class="evento-postcontent evento-postcontent-0 clearfix">
                                                        <div class="evento-content-layout">
                                                            <div class="evento-content-layout-row">
                                                                <div class="evento-layout-cell layout-item-0" style="width: 100%">
                                                                    <div class='ui-widget hide' id="events-error">
                                                                        <div class='ui-state-error ui-corner-all' style='margin-top: 20px; padding: 0 .7em;'>
                                                                            <p><span class='ui-icon ui-icon-alert' style='float: left; margin-right: .3em;'></span>
                                                                            <b class="error-text"></b></p>
                                                                        </div>
                                                                        <br>
                                                                    </div>
                                                                    <form id="frmEventsChanges">
                                                                        <span class="col-sm-4">Azienda:</span>
                                                                        <span class="col-sm-8"><input type="text" id="txtCompany" value="" class="form-control" /></span>
                                                                        <br>
                                                                        <span class="col-sm-4">Categorie preferite: 
                                                                        <br><i style="font-size:9px">Inserisci i nuovi TAG separati da una virgola.</i>
                                                                        </span>
                                                                        <span class="col-sm-8">
                                                                            <span id="tag-list"></span>
                                                                            <br>                        
                                                                            <div class="input-group">
                                                                                <input type="text" id="txtAddTag" class="form-control" placeholder="Nuovi TAG">
                                                                                <span id="btnAddTag" class="input-group-addon"><span class="glyphicon glyphicon-plus"></span></span>
                                                                            </div>
                                                                        </span>
                                                                        <br>
                                                                        <span class="col-sm-12" style="text-align:center"><input type="submit" class="evento-button" value="Salva Modifiche"/></span>
                                                                    </form>
                                                                </div>
                                                            </div>
                                                        </div>
                                                    </div>
                                                </article>
                                                
                                                <article class="evento-post evento-article">
                                                    <div class="evento-postmetadataheader">
                                                        <h2 class="evento-postheader">Password</h2>
                                                    </div>
                                                    <div class="evento-postcontent evento-postcontent-0 clearfix">
                                                        <div class="evento-content-layout">
                                                            <div class="evento-content-layout-row">
                                                                <div class="evento-layout-cell layout-item-0" style="width: 100%">
                                                                    <div class='ui-widget hide' id="pwd-error">
                                                                        <div class='ui-state-error ui-corner-all' style='margin-top: 20px; padding: 0 .7em;'>
                                                                            <p><span class='ui-icon ui-icon-alert' style='float: left; margin-right: .3em;'></span>
                                                                            <b class="error-text"></b></p>
                                                                        </div>
                                                                        <br>
                                                                    </div>
                                                                    <form id="frmPasswordChanges">
                                                                        <span class="col-sm-4">Vecchia password:</span>
                                                                        <span class="col-sm-8"><input type="password" id="txtPwdOld" class="form-control" /></span>
                                                                        <br>
                                                                        <span class="col-sm-4">Nuova password:</span>
                                                                        <span class="col-sm-8"><input type="password" id="txtPwdNew1" class="form-control" /></span>
                                                                        <br>
                                                                        <span class="col-sm-4">Ripeti nuova password:</span>
                                                                        <span class="col-sm-8"><input type="password" id="txtPwdNew2" class="form-control" /></span>
                                                                        <br>
                                                                        <span class="col-sm-12" style="text-align:center"><input type="submit" class="evento-button" value="Salva Modifiche"/></span>
                                                                    </form>
                                                                </div>
                                                            </div>
                                                        </div>
                                                    </div>
                                                </article>
                                            </div>
                                        </div>
                                    </div>
                                </article>
                            </div>

                            <!-- sidebar -->
                            <jsp:include page="html/sidebar.jsp" />
                            <!-- /sidebar -->

                        </div>
                    </div>
                </div>

                <!-- footer -->
                <%@include file="html/footer.jsp" %>
                <!-- /footer -->

            </div>
        </div>
        
        <!-- modal windows -->
        <%@include file="html/modal.jsp" %>
        <!-- /modal windows -->
    </body>
</html>
